const {
    toUrl,
    globalData,msgLoading
} = getApp()
import {
    request
} from "@/utils/request"
Page({
    toUrl,
    data: {
        globalData,
        current: 0,
        activeId: null,
        detail: {},
        userinfo: null,
        headBc: '',
        act: '/img/act3.png',
        poster:null,shareShow:false,
        loading:true

    },
    handleShare() {
        // console.log(this.data.detail.images.length);
        if (this.data.detail.images.length == 0) {
            wx.showToast({
              title: '未上传商品图，请上传',
              icon:'none'
            })
            return
        }
        this.shows()
    },
    shows: function () {
        // wx.showToast({
        //     title: '生成海报中...',
        //     icon: "loading",
        //     mask: true,
        // })
        this.setData({
            shareShow: true
        })
        this.drawPoster()
    },
    drawPoster() {
        const query = wx.createSelectorQuery()
        const self = this;
        //...判断本地信息，引导用户授权获取头像部分

        query.select('#myCanvas')
            .fields({
                node: true,
                size: true
            })
            .exec(async (res) => {
                self.canvas = res[0].node
                self.ctx = self.canvas.getContext('2d')
                //屏幕像素比
                const dpr = wx.getSystemInfoSync().pixelRatio
                self.canvas.width = res[0].width * dpr
                self.canvas.height = res[0].height * dpr
                //画布放大后绘制比例也相应放大，这样绘图时就能按原尺寸计算
                self.ctx.scale(dpr, dpr)
                //...画布适配部分
                //背景
                self.ctx.fillStyle = '#fff'
                self.ctx.fillRect(0, 0, self.canvas.width, self.canvas.height)
                // self.ctx.fillStyle='pink'
                // self.ctx.fillRect(0, 0, 300, 300)
                //...背景及文字绘制部分
                //文字
                self.ctx.textBaseline = 'top'
                self.ctx.textAlign = 'left'
                self.ctx.fillStyle = '#000'
                self.ctx.font = '16px  Helvertica'
                self.ctx.fillText("分享你一个活动", 10, 15)
                wx.showLoading({
                    title: '海报生成中'
                });
                //获取头像和二维码和背景图
                //  self.getBgImg()
                const result = await Promise.all([self.getQrcode(), self.getBgImg()]).catch((err) => {
                    console.log(err);
                })

                console.log(result);
                if (result == undefined) {
                    wx.showToast({
                        title: '未上传主图图片',
                        icon: 'none'
                    })
                    // wx.hideLoading()
                    setTimeout(() => {
                        self.setData({
                            shareShow: false
                        })
                    }, 1500);

                }
                await Promise.all([self.drawQRcode2(result[0]), self.drawBgImg(result[1]), self.drawTitle()])

                wx.hideLoading()
                //将canvas转化成临时路径，用imge加载生成图片呈现在页面
                self.canvas2Img()
            })
    },

    canvas2Img() {
        const self = this
        console.log(55555);
        setTimeout(() => {
            //将画布保存成临时路径 供展示
            wx.canvasToTempFilePath({
                //因为是2d所以需要传入整个canvas节点
                canvas: self.canvas,
                success: (res) => {
                    //将路径保存下来通过image在页面上展示
                    console.log(res);
                    this.setData({
                        poster: res.tempFilePath
                    })
                    //   self.poster = 
                },
                fail: (res) => {
                    console.log(`fail`, res)
                }
            }, self)
        }, 200)
    },
    //获取小程序二维码
    getQrcode() {
        console.log(11122888);
        return new Promise((resolve, reject) => {
            let errorData = {
                code: 0,
                msg: '请求失败: 1.未上传主图图片;2.二维码绘制失败'
            }
            let successData = {
                code: 1,
                msg: '请求成功'
            }

            let pages = getCurrentPages() //获取加载的页面
            let currentPage = pages[pages.length - 1] //获取当前页面的对象
            let url = currentPage.route //当前页面url
            let options = currentPage.options //如果要获取url中所带的参数可以查看options
            let urlWithArgs = url + '?'
            for (let key in options) {
                let value = options[key]
                urlWithArgs += key + '=' + value + '&'
            }
            urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1)

            console.log(urlWithArgs);

            let data = {
                typeid: 3,
                scene: '?activity_id=' + this.data.activeId
            }
            request('currency/getwxacodeunlimit', {
                data
            }).then(res => {
                console.log(res);

                resolve(res.data.qrcode)

            }).catch((err) => {
                reject(errorData)
            })

        })
    },
    //计算文本超出超短函数
    getTextCt(str) {
        const self = this;
        console.log(self.canvas.width)
        let canvasWidth = self.canvas.width
        let fontSize = parseInt((wx.getSystemInfoSync().windowWidth / 375) * 30)
        let rowFontNum = Math.floor(canvasWidth / fontSize)
        let strLength = str.length
        let rows = Math.ceil(strLength / rowFontNum)
        return {
            canvasWidth,
            fontSize,
            rowFontNum,
            strLength,
            rows
        }
    },
     //绘制商品标题
     drawTitle() {
        const self = this;
        const dpr = wx.getSystemInfoSync().pixelRatio

        let height = self.canvas.height / dpr
        let chazhi = height - 100
        console.log(chazhi);
        // const context = wx.createCanvasContext('myCanvas')
        var text = this.data.detail.name; //这是要绘制的文本
        // var text = '你好你好你好单独你好你好你好单独你好你好你好单独你好你好你好单独'; //这是要绘制的文本
        var chr = text.split(""); //这个方法是将一个字符串分割成字符串数组
        var temp = "";
        var row = [];
        let len = 0
        self.ctx.font = 'bold  14px Helvertica'

        self.ctx.fillStyle = '#000'

        for (var a = 0; a < chr.length; a++) {
            if (self.ctx.measureText(temp).width < 170) {
                temp += chr[a];
            } else {
                a--; //这里添加了a-- 是为了防止字符丢失，效果图中有对比
                row.push(temp);
                temp = "";
            }
        }
        row.push(temp);

        //如果数组长度大于2 则截取前两个
        if (row.length > 2) {
            console.log(99999999);
            var rowCut = row.slice(0, 2);
            var rowPart = rowCut[1];
            var test = "";
            var empty = [];
            for (var a = 0; a < rowPart.length; a++) {
                if (self.ctx.measureText(test).width < 170) {
                    test += rowPart[a];
                } else {
                    break;
                }
            }
            empty.push(test);
            var group = empty[0] + "..." //这里只显示两行，超出的用...表示
            rowCut.splice(1, 1, group);
            row = rowCut;
        }
        console.log(row);
        if (row.length > 1) {
            len = 0
        } else {
            len = 10

        }
        for (var b = 0; b < row.length; b++) {
            self.ctx.fillText(row[b], 10, chazhi + 25 + b * 30 + len, 170);
        }
    },

    //绘制二维码图像
    drawQRcode2(bufferData) {
        const self = this;
        const dpr = wx.getSystemInfoSync().pixelRatio
        let wid = self.canvas.width / dpr
        let height = self.canvas.height / dpr
        let chazhi = height - 140

        return new Promise((resolve, reject) => {
            let image = self.canvas.createImage();
            //加载buffer数据
            image.src = bufferData;
            image.onload = () => {
                self.ctx.drawImage(image, wid - 90, chazhi + 50, 80, 80);
                resolve()
            }
        })
    },
     //绘制背景图
     drawBgImg(src) {
        const self = this;
        const dpr = wx.getSystemInfoSync().pixelRatio
        const width = self.canvas.width / dpr
        const height = self.canvas.height / dpr
        console.log(width, height);
        return new Promise((resolve, reject) => {
            let image = self.canvas.createImage();
            image.src = src;
            image.onload = (res) => {
                self.ctx.drawImage(image, 0, 40, width,  height - 140);
                resolve()
            }

        })
    },
    //获取背景图
    getBgImg() {
        const self = this
        return new Promise((resolve, reject) => {
            let errorData = {
                code: 0,
                msg: '请求失败: 1.未上传主图图片;2.二维码绘制失败'
            }
            let successData = {
                code: 1,
                msg: '请求成功'
            }
            let imglist = self.data.detail.images
            if (imglist.length == 0) {
                // console.log(9999999);
                reject(errorData)
            } else {
                resolve(imglist[0], successData)
            }
        })
    },
    //处理头部滚动事件
    onPageScroll(e) {
        const scrollTop = e.scrollTop
        if (scrollTop > 150) {
            this.setData({
                headBc: 'headbc',
                act: '/image/icon-arrow-left.png'
            })
        } else {
            this.setData({
                headBc: '',
                act: '/img/act3.png'
            })
        }
    },
    changeSwiper({
        detail
    }) {
        const {
            current
        } = detail
        this.setData({
            current
        })
    },
    getActiveDeatail(id) {
        const that = this
        const data = {
            activity_id: this.data.activeId ? this.data.activeId : id
        }
        request('activity/activityinfo', {
            data
        }).then(res => {
						console.log(res)
						let contents
            let zhengze = new RegExp('<img', 'g')
						let zhengze1 = new RegExp('<p', 'g')
            contents = res.data.content.replace(zhengze1, '<p style="width:100%;height:auto;display:block;margin:10px 0;" ')
            contents = contents.replace(zhengze, '<img style="width:100%;height:auto;display:block;" ')
            res.data.content = contents
            that.setData({
                detail: res.data,
                loading:false
            })
        }).finally(()=>{
            wx.hideLoading()
        })
    },
    //获取用户信息
    getUserInfo() {
        const that = this
        return request('user/getuserinfo').then(res => {
            that.setData({
                userinfo: res.data
            })
        })
    },
    gotoApply(e) {
        console.log(this.data.detail.status);
        if (this.data.detail.is_apply == 1) {
            // wx.showToast({
            //     icon: 'none',
            //   title: '已报名',
            // })
            return
        }
        if (this.data.detail.num == 0) {
            // wx.showToast({
            //     icon: 'none',
            //   title: '已报名',
            // })
            return
        }
        if(this.data.detail.status == 1) {
            // wx.showToast({
            //     icon: 'none',
            //   title: '报名已结束',
            // })
            return
        }
        // if(this.data.detail.status == 2) {
        //     wx.showToast({
        //         icon: 'none',
        //       title: '报名已结束',
        //     })
        //     return
        // }
        const that = this
        if (this.data.detail.is_apply == 1) {
            return
        } else { //处理门栏和积分数的情况
            console.log(this.data.detail.status);
            if (this.data.detail.status == 2) {
                // wx.showToast({
                //     icon: 'none',
                //   title: '报名或活动已结束',
                // })
                return
            }
            this.getUserInfo().then(res => {
                const userinfo = that.data.userinfo
                const detail = that.data.detail
                if (Number(userinfo.level.slice(userinfo.level.length - 1, userinfo.level.length)) >= detail.level && userinfo.integral >= detail.integral) {
                    const url = e.currentTarget.dataset.url
                    wx.navigateTo({
                        url: url,
                    })
                } else {
                    wx.showToast({
                        icon: 'error',
                        title: '会员或积分不足',
                    })
                }
            })

        }
    },
    onLoad(options) {
        msgLoading()
        console.log(options);
        let activeId = ''
        if (options.activity_id == undefined) {
            activeId = decodeURIComponent(options.scene).split('?')[1].split('=')[1]
        }else{
            activeId = options.activity_id
        }
        this.setData({
            activeId: activeId
        })
    },

    onReady() {},

    onShow() {
        if (this.data.activeId) {
            console.log('存在')
            this.getActiveDeatail(this.data.activeId)
        }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})